<template>
  <div class="home-add">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ formTitle }}</span>
        </div>
      </template>
      <div class="form-container">
        <el-form
          :model="homeForm"
          :rules="rules"
          ref="homeFormRef"
          label-width="120px"
          :disabled="formDisabled"
          v-loading="loading"
        >
          <el-form-item label="所属小区" prop="communityId">
            <el-select v-model="homeForm.communityId" placeholder="请选择小区" @change="loadBuildings">
              <el-option 
                v-for="community in communities" 
                :key="community.id" 
                :label="community.name" 
                :value="community.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属栋数" prop="buildingId">
            <el-select v-model="homeForm.buildingId" placeholder="请选择栋数">
              <el-option 
                v-for="building in buildings" 
                :key="building.id" 
                :label="building.name" 
                :value="building.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房产名称" prop="name">
            <el-input v-model="homeForm.name" placeholder="请输入房产名称"></el-input>
          </el-form-item>
          <el-form-item label="楼层" prop="floor">
            <el-input-number v-model="homeForm.floor" :min="1" :precision="0"></el-input-number>
          </el-form-item>
          <el-form-item label="面积(平方米)" prop="area">
            <el-input-number v-model="homeForm.area" :min="1" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
          <el-form-item label="户型" prop="type">
            <el-select v-model="homeForm.type" placeholder="请选择户型">
              <el-option label="一室一厅" value="一室一厅"></el-option>
              <el-option label="两室一厅" value="两室一厅"></el-option>
              <el-option label="三室一厅" value="三室一厅"></el-option>
              <el-option label="三室两厅" value="三室两厅"></el-option>
              <el-option label="四室两厅" value="四室两厅"></el-option>
              <el-option label="复式" value="复式"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="朝向" prop="direction">
            <el-select v-model="homeForm.direction" placeholder="请选择朝向">
              <el-option label="东" value="东"></el-option>
              <el-option label="南" value="南"></el-option>
              <el-option label="西" value="西"></el-option>
              <el-option label="北" value="北"></el-option>
              <el-option label="东南" value="东南"></el-option>
              <el-option label="东北" value="东北"></el-option>
              <el-option label="西南" value="西南"></el-option>
              <el-option label="西北" value="西北"></el-option>
              <el-option label="南北通透" value="南北通透"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入住状态" prop="status">
            <el-select v-model="homeForm.status" placeholder="请选择入住状态">
              <el-option label="未入住" value="未入住"></el-option>
              <el-option label="已入住" value="已入住"></el-option>
              <el-option label="已出租" value="已出租"></el-option>
              <el-option label="装修中" value="装修中"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="业主" prop="ownerId">
            <el-select v-model="homeForm.ownerId" placeholder="请选择业主" filterable>
              <el-option 
                v-for="owner in owners" 
                :key="owner.id" 
                :label="owner.name" 
                :value="owner.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'HomeAdd',
  data() {
    return {
      formTitle: '添加房产',
      formDisabled: false,
      loading: false,
      communities: [],
      buildings: [],
      owners: [],
      homeForm: {
        id: null,
        name: '',
        floor: 1,
        area: 50,
        type: '',
        direction: '',
        status: '未入住',
        buildingId: '',
        communityId: '',
        ownerId: ''
      },
      rules: {
        communityId: [
          { required: true, message: '请选择所属小区', trigger: 'change' }
        ],
        buildingId: [
          { required: true, message: '请选择所属栋数', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入房产名称', trigger: 'blur' }
        ],
        floor: [
          { required: true, message: '请输入楼层', trigger: 'change' }
        ],
        area: [
          { required: true, message: '请输入面积', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择户型', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择朝向', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择入住状态', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    // 加载小区列表
    this.fetchCommunities();
    // 加载业主列表
    this.fetchOwners();
    
    // 如果是编辑，则获取ID并加载数据
    const id = this.$route.query.id;
    if (id) {
      this.formTitle = '编辑房产';
      this.loadHomeData(id);
    }
  },
  methods: {
    // 获取小区列表
    fetchCommunities() {
      axios.get('/api/communities')
        .then(response => {
          this.communities = response.data;
        })
        .catch(error => {
          console.error('获取小区列表失败:', error);
          ElMessage.error('获取小区列表失败');
        });
    },
    
    // 获取业主列表
    fetchOwners() {
      axios.get('/api/owners')
        .then(response => {
          this.owners = response.data;
        })
        .catch(error => {
          console.error('获取业主列表失败:', error);
          ElMessage.error('获取业主列表失败');
        });
    },
    
    // 根据小区ID加载楼栋列表
    loadBuildings(communityId) {
      if (!communityId) {
        this.buildings = [];
        this.homeForm.buildingId = '';
        return;
      }
      
      axios.get(`/api/buildings/community/${communityId}`)
        .then(response => {
          this.buildings = response.data;
        })
        .catch(error => {
          console.error('获取楼栋列表失败:', error);
          ElMessage.error('获取楼栋列表失败');
        });
    },
    
    // 加载房产详情数据
    loadHomeData(id) {
      this.loading = true;
      axios.get(`/api/homes/${id}`)
        .then(response => {
          const homeData = response.data;
          
          // 设置小区ID并加载楼栋
          if (homeData.building && homeData.building.community) {
            this.homeForm.communityId = homeData.building.community.id;
            this.loadBuildings(this.homeForm.communityId);
          }
          
          // 设置表单数据
          this.homeForm = {
            id: homeData.id,
            name: homeData.name,
            floor: homeData.floor,
            area: homeData.area,
            type: homeData.type,
            direction: homeData.direction,
            status: homeData.status,
            buildingId: homeData.building ? homeData.building.id : '',
            ownerId: homeData.owner ? homeData.owner.id : ''
          };
          
          this.loading = false;
        })
        .catch(error => {
          console.error('获取房产信息失败:', error);
          ElMessage.error('获取房产信息失败');
          this.loading = false;
        });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.homeFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          
          // 构建提交数据
          const submitData = {
            name: this.homeForm.name,
            floor: this.homeForm.floor,
            area: this.homeForm.area,
            type: this.homeForm.type,
            direction: this.homeForm.direction,
            status: this.homeForm.status,
            building: { id: this.homeForm.buildingId },
            owner: this.homeForm.ownerId ? { id: this.homeForm.ownerId } : null
          };
          
          // 如果是编辑，添加ID
          if (this.homeForm.id) {
            submitData.id = this.homeForm.id;
          }
          
          // 提交数据
          const method = this.homeForm.id ? 'put' : 'post';
          const url = this.homeForm.id ? `/api/homes/${this.homeForm.id}` : '/api/homes';
          
          axios[method](url, submitData)
            .then(response => {
              ElMessage.success(this.homeForm.id ? '编辑成功' : '添加成功');
              this.loading = false;
              this.goBack();
            })
            .catch(error => {
              console.error('保存房产失败:', error);
              if (error.response && error.response.data && error.response.data.message) {
                ElMessage.error(error.response.data.message);
              } else {
                ElMessage.error('保存房产失败');
              }
              this.loading = false;
            });
        } else {
          ElMessage.error('表单验证失败，请检查必填项');
          return false;
        }
      });
    },
    
    // 返回列表页
    goBack() {
      this.$router.push('/property/home');
    }
  }
};
</script>

<style scoped>
.home-add {
  padding: 20px;
}
.form-container {
  max-width: 800px;
  margin: 0 auto;
}
</style>
